#include <iostream>
#define N 10
#include <string.h>

int main() {
    void input(int num[], char name[N][8]);
    void sort(int num[], char name[N][8]);
    void search(int n, int num[], char name[N][8]);
    int num[N], number, flag = 1, c;
    char name[N][8];
    input(num, name);
    sort(num, name);
    while (flag == 1) {
        printf("input number to look for:");
        scanf("%d", &number);
        search(number, num, name);
        printf("continue or not(Y/N)?");
        getchar();
        c = getchar();
        if (c == 'N' || c == 'n')
            flag = 0;
    }
    return 0;
}

void input(int num[], char name[N][8]) {    //输入数据
    int i;
    for (i = 0; i < N; i++) {
        printf("input No.:");
        scanf("%d", &num[i]);
        printf("Input name:");
        getchar();
        gets(name[i]);
    }
}

void sort(int num[], char name[N][8]) {     //排序
    int i, j, min, temp1;
    char temp2[8];
    for (i = 0; i < N; i++) {
        min = i;
        for (j = i; j < N; j++) {
            if (num[min] > num[j]) min = j;
        }
        temp1 = num[i];
        strcpy(temp2, name[i]);
        num[i] = num[min];              // 交换编号
        strcpy(name[i], name[min]);     // 交换姓名
        num[min] = temp1;               // 将较小的数据传给i元素后，完成一次排序，将之前较大的数继续赋值为min，与后面比较
        strcpy(name[min], temp2);
    }
    printf("\n result: \n");
    for (i = 0; i < N; i++) {
        printf("\n %5d%10s", num[i], name[i]);
    }
    printf("\n");
}

void search(int n, int num[], char name[N][8]) {        // 折半法查找元素
    int top, bott, mid, loca, sign;
    top = 0;
    bott = N - 1;
    loca = 0;       // 元素所在的下标编号
    sign = 1;
    if ((n < num[0]) || (n > num[n - 1])) {
        loca = -1;       // 编号不在范围内，loca=-1 表示不存在
    }
    while ((sign == 1) && (top < bott)) {
        mid = (top + bott) / 2;
        if (n == num[mid]) {
            loca = mid;
            printf("NO.%d, his name is %s.\n", n, name[loca]);
            sign = -1;          // 查找到数据后，令sign = -1;结束循环
        }
        else if (n < num[mid])
            bott = mid - 1;
        else
            top = mid + 1;
    }
    if (sign == 1 || loca == -1) {
        printf("%d does not exist!\n");
    }
}
























